/*
 * Copyright (C) 2010 ZXing authors
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

package com.scaner.sam.decode;

import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.scaner.sam.R;
import com.scaner.sam.ui.ScanerActivity;
import com.scaner.sam.general.RecogResult;

import cn.bertsir.zbar.utils.QRUtils;

final class DecodeHandler extends Handler {

    private  ScanerActivity mActivity;
    private String TAG ="DecodeHandler";
    DecodeHandler(ScanerActivity activity) {
        this.mActivity = activity;
    }
    @Override
    public void handleMessage(Message message) {
        if(message.what == R.id.decode){
            decode((byte[]) message.obj, message.arg1, message.arg2);
        }else if(message.what == R.id.quit){
            Looper looper = Looper.myLooper();
            if (null != looper) {
                looper.quit();
            }
        }
    }

    private void decode(byte[] data, int width, int height) {
        mActivity.setIsAvailable(false);
        try{
            int rot = 90;
            Rect orgRect = mActivity.getCropRect();

            Log.i("SamTam",width+"----"+height+"====="+orgRect.width()+"---"+orgRect.height());
            Bitmap recogBitmap = makeCropedGrayBitmap(data, width, height, 90, orgRect);
            long start = System.currentTimeMillis();
            RecogResult rawResult;

            if (mActivity.isQrCodeOne()){
                rawResult = new RecogResult();
                try {
                    String res = QRUtils.getInstance().decodeBarcode(recogBitmap);
                    rawResult.m_lineNumber = res;
                    rawResult.m_nRecogTime = (System.currentTimeMillis() - start);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }else {
                rawResult = QRUtils.getInstance().myEngine.RecogPhoneNumber_data(data, width, height, rot, orgRect);
                rawResult.m_nRecogTime = (System.currentTimeMillis() - start);
            }

            if(rawResult!=null){
                if(mActivity.isQrCodeOne()){
                    if (rawResult.m_lineNumber !=null) {
                        postHandle(rawResult);
                    }else {
                        posHandleFail();
                    }
                }else {
                    if (rawResult.m_nResultCount > 0) {
                        postHandle(rawResult);
                    } else {
                        posHandleFail();
                    }
                }
            }else {
                posHandleFail();
            }
        }catch (Exception e){
            posHandleFail();
        }
        mActivity.setIsAvailable(true);
    }

    private Bitmap cropBitmap(Bitmap bitmap,Rect rect) {
        int w = bitmap.getWidth(); // 得到图片的宽，高
        int h = bitmap.getHeight();
        return Bitmap.createBitmap(bitmap, rect.left, 0, rect.width(), rect.height(), null, false);
    }


    private void posHandleFail(){
        Message messageFail = Message.obtain(mActivity.getCaptureActivityHandler(), R.id.decode_failed);
        messageFail.sendToTarget();

    }

    private void postHandle(RecogResult rawResult){
        Message message = Message.obtain(mActivity.getCaptureActivityHandler(), R.id.decode_succeeded, rawResult);
        message.sendToTarget();

    }
    public static Bitmap makeCropedGrayBitmap(byte[] data, int width, int height, int rot, Rect cropRect) {
        int cropwidth = cropRect.width();
        int cropheight = cropRect.height();
        int[] pixels = new int[cropwidth * cropheight];
        int grey, inputOffset, outputOffset, temp;
        byte[] yuv = data;

        if (rot == 0) {
            inputOffset = cropRect.top * width;
            for (int y = 0; y < cropheight; y++) {
                outputOffset = y * cropwidth;
                for (int x = 0; x < cropwidth; x++) {
                    grey = yuv[inputOffset + x + cropRect.left] & 0xff;
                    pixels[outputOffset + x] = 0xFF000000 | (grey * 0x00010101);
                }
                inputOffset += width;
            }
        } else if (rot == 90) {
            int x, y, x1, y1;
            for (y = 0; y < cropheight; y++) {
                y1 = cropRect.top + y;
                for (x = 0; x < cropwidth; x++) {
                    x1 = cropRect.left + x;
                    grey = yuv[y1 * width + x1] & 0xff;
                    pixels[x * cropheight + cropheight - y - 1] = 0xFF000000 | (grey * 0x00010101);
                }

            }
            temp = cropwidth;
            cropwidth = cropheight;
            cropheight = temp;
        }
        Bitmap bitmap = Bitmap.createBitmap(cropwidth, cropheight, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, cropwidth, 0, 0, cropwidth, cropheight);

        pixels = null;
        yuv = null;

        return bitmap;
    }
}
